package com.ks.winterwarmimage;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.TextView;

import com.ks.winterwarmimage.adapter.AccountAdapter;
import com.ks.winterwarmimage.adapter.DevItem;
import com.ks.winterwarmimage.adapter.DeviceAdapter;
import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.esptouch.EspTouchManage;
import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.mqtt.MsgMqttService;
import com.ks.winterwarmimage.utils.BasicsUtil;
import com.ks.winterwarmimage.utils.CmdDataPacket;
import com.ks.winterwarmimage.utils.Constants;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.List;
/**
 * 查询已绑定的设备列表，在已知账户ID的情况下，查询已绑定的设备列表，并且将其存储到数据库中
 */
public class LoadBindDevActivity extends BaseActivity implements View.OnClickListener{
    private static final String TAG="LoadBindDevActivity";
    private static final String base_topic="WinterWarmImage/dev/";
    private TextView textAccount;
    private ListView listQuery;
    private List<DevItem> deviceItems;
    private DeviceAdapter adapter;
    private List<AccountAdapter.Account> accountList=null;
    private int currentPosition=-1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_load_bind_dev);
        ((TextView)findViewById(R.id.text_title)).setText(R.string.load_bin_dev);
        textAccount = findViewById(R.id.text_account_id);
        initData();
        findViewById(R.id.img_return).setOnClickListener(this);
        findViewById(R.id.btn_query_bind).setOnClickListener(this);
        findViewById(R.id.btn_save_to).setOnClickListener(this);
        findViewById(R.id.linear_account).setOnClickListener(this);
        bindMqttService();          //绑定MQTT服务
    }
    @Override
    protected void onDestroy() {
        unMqttBroadcastReceiver();    //解除MQTT服务
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.e(TAG,"按下Back或Home键退出");
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.img_return){
            finish();
        }else if(view.getId()==R.id.btn_query_bind){
            if(!TextUtils.isEmpty(textAccount.getText()) && textAccount.getText().length()>0) {
                byte[] accountId = textAccount.getText().toString().getBytes(EspTouchManage.GB2312);
                CmdDataPacket cmd = new CmdDataPacket(CmdDataPacket.CMD_QUERY_BIND_DEV,  accountId);
                if(MsgMqttService.getMqttConnect()) {         //推送消息的前提时必须连接到MQTT服务器
                    String topic = "WinterWarmImage/phone/global";
                    MqttMessage cmdMag = new MqttMessage(cmd.toBytes());
                    MsgMqttService.publish(topic, cmdMag);
                }
            }
        }else if(view.getId()==R.id.btn_save_to){
            List<ContentValues> values = new ArrayList<>();
            String accountId=textAccount.getText().toString();
            for(DevItem item:deviceItems){
                ContentValues value=new ContentValues();
                value.put(Constants.KEY_MAC_ID,item.deviceId.toLowerCase());
                value.put(Constants.KEY_DEV_NAME,item.devName);
                value.put(Constants.KEY_ACCOUNT_ID,accountId);
                values.add(value);
            }
            int result = DatabaseManager.insertWithOnConflict(Constants.TABLE_DEV,values, SQLiteDatabase.CONFLICT_REPLACE);
            Log.e(TAG,"写入的组信息数:"+result);
            DatabaseManager.updateCurrentAccountPosition(currentPosition);   //更新账户位置
            this.setResult(RESULT_CODE+1);
            finish();
        }else if(view.getId()==R.id.linear_account){
            showListPopup(view);     //显示账户列表
        }
    }

    @Override
    protected void onMessageArrived(MqttMag message) {
        super.onMessageArrived(message);
        CmdDataPacket cmdDataPacket = CmdDataPacket.fromBytes(message.getMessage());
        if(cmdDataPacket!=null && cmdDataPacket.command==CmdDataPacket.CMD_QUERY_BIND_DEV_ACK) {
            byte[] accountBuff= BasicsUtil.subByte(cmdDataPacket.data,0,8);  //账号ID
            String account = new String(accountBuff, EspTouchManage.GB2312); //将字节数组转换为字符串
            String queryAccount=textAccount.getText().toString();
            if(queryAccount.equalsIgnoreCase(account)){
                String topic = message.getTopic().replace(base_topic, "");  //去掉基主题部分
                String bssid = BasicsUtil.addMacColon(topic);                         //得到设备地址
                //获取组名称字符串的结束符位置'\0'
                int null_position= -1;
                for(int i=8;i<cmdDataPacket.data.length;i++){
                    if(cmdDataPacket.data[i]==0x00){
                        null_position=i;
                        break;
                    }
                }
                byte[] devNameBuff;   //存放组名称字节缓冲区
                if(null_position>8){
                    devNameBuff= BasicsUtil.subByte(cmdDataPacket.data,8,null_position-8);
                }else{
                    devNameBuff= BasicsUtil.subByte(cmdDataPacket.data,8);
                }
                String devName = new String(devNameBuff, EspTouchManage.GB2312); //将字节数组转换为字符串
                boolean exist = false;   //用于标识重叠数据
                for(DevItem item:deviceItems){
                    if(item.deviceId.equals(bssid)){
                        exist=true;
                        break;
                    }
                }
                if(!exist) {                              //只对不存在的数据才添加
                    deviceItems.add(new DevItem(bssid, devName));   //将数据添加到列表
                    adapter.notifyDataSetChanged();               //通知适配器更新显示
                }
            }

        }
    }

    /**
     * 初始化适配器及数据列表
     */
    private void initData(){
        listQuery = findViewById(R.id.list_query);
        deviceItems=new ArrayList<>();
        adapter=new DeviceAdapter(this,deviceItems);
        listQuery.setAdapter(adapter);
    }
    /**
     * 显示账户列表
     * @param v 触发的控件
     */
    @SuppressLint("UseCompatLoadingForDrawables")
    private void showListPopup(View v) {
        if(accountList==null) {
            accountList = new ArrayList<>();
            List<String> accountIds = DatabaseManager.getAccountList();
            //int currentPosition = DatabaseManager.getCurrentAccountPosition();
            if (accountIds != null && accountIds.size() > 0) {
                for (int i = 0; i < accountIds.size(); i++) {
                    AccountAdapter.Account account = new AccountAdapter.Account(accountIds.get(i), false);
                    accountList.add(account);
                }
            }
        }
        AccountAdapter adapterAccount=new AccountAdapter(this,accountList);
        //创建列表对话框
        ListPopupWindow listPopupWindow=new ListPopupWindow(this);
        listPopupWindow.setBackgroundDrawable(getDrawable(R.drawable.rounded_corners));
        listPopupWindow.setAnchorView(v);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT); //设置宽度
        listPopupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindow.setModal(true);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setAdapter(adapterAccount);
        listPopupWindow.setOnItemClickListener((parent, view, position, id)->{
            currentPosition=position;
            adapterAccount.selectItem(position);
            textAccount.setText(accountList.get(position).accountId);
            deviceItems.clear();
            adapter.notifyDataSetChanged();
            listPopupWindow.dismiss();
        });
        listPopupWindow.show();
    }
}